<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';

import { computed, ref } from 'vue';

import { Plus } from '@vben/icons';

import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  addAccount,
  deleteAccountByID,
  editAccount,
  reqAccountDetail,
  reqAccountList,
  reqGroupList,
  reqInitAccount,
  reqPlatformList,
} from '#/api/exchange-center';

import BatchAdd from './components/BatchAdd.vue';
import { collectGroups } from './utils';

interface IPlatform {
  id: number;
  name: string;
}

const curPlatform = ref();
const curPlatformID = ref<number>(0);
const platformList = ref<IPlatform[]>([]);
const getPlatformList = async () => {
  const res = await reqPlatformList();
  platformList.value = res.list;
  // 初始化设置为 平台数组的第一个
  curPlatform.value = res.list[0];
  curPlatformID.value = res.list[0].id;
  gridApi.reload();
};
getPlatformList();

interface RowType {
  id: number;
  ip: string;
  remark: string;
  groups: string;
  platforms: string;
  account: string;
  status: boolean;
  connect: boolean;
  default: boolean;
  updated_at: string;
}
const gridOptions: VxeGridProps<RowType> = {
  columns: [
    { title: '挂靠IP', field: 'ip', width: 140 },
    { title: '账号备注', field: 'remark', width: 120 },
    { title: '组别', field: 'groups' },
    { title: '平台', field: 'platforms', width: 120 },
    { title: 'uid', field: 'account' },
    { title: '状态', field: 'status', slots: { default: 'status' } },
    { title: '连接状态', field: 'connect', slots: { default: 'connect' } },
    { title: '初始化', field: 'init', slots: { default: 'init' } },
    { title: '状态更新时间', field: 'updated_at', slots: { default: 'time' } },
    { slots: { default: 'action' }, title: '操作', width: 200 },
  ],
  pagerConfig: {
    enabled: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        if (curPlatformID.value) {
          const res = await reqAccountList({
            page: page.currentPage,
            limit: page.pageSize,
            platform_id: curPlatformID.value,
          });
          return {
            items: res.list,
            total: res.total,
          };
        } else {
          return {
            items: [],
            total: 0,
          };
        }
      },
    },
    sort: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

const reload = () => {
  gridApi.reload();
};

// 账号初始化
const initAccount = async (id: number, type = 'single') => {
  ElMessageBox.confirm('确定进行初始化操作?', '提示', {
    type: 'warning',
  }).then(async () => {
    await reqInitAccount({
      id: type === 'single' ? id : '',
      platform_id: curPlatformID.value,
    });
    ElMessage({ type: 'success', message: '操作成功' });

    reload();
  });
};
const dialogVisible = ref(false);

const handlePlatformChange = (val: number) => {
  curPlatformID.value = val;
  curPlatform.value = platformList.value.find((item) => item.id === val);
  reload();
};

/** 编辑开始 */
const isOkxSwap = computed(() => {
  return curPlatform.value.name === 'OkxSwap';
});
const isAddType = ref(false);
const curRowData = ref({
  id: 0,
  ip: '',
  remark: '',
  groups: '',
  platforms: '',
  platform_id: '',
  account: '',
  status: false,
  connect: false,
  default: false,
  updated_at: '',
  group_id: '',
  api_key: '',
  api_secret: '',
  passphrase: '',
});

const dataRules = ref({
  ip: [
    { required: true, message: '请输入', trigger: 'blur' },
    { max: 256, message: '长度必须小于256位', trigger: 'blur' },
  ],
  group_id: [{ required: true, message: '请输入', trigger: 'blur' }],
  account: [
    { required: true, message: '请输入', trigger: 'blur' },
    { max: 256, message: '长度必须小于256位', trigger: 'blur' },
  ],
  api_key: [{ required: true, message: '请输入', trigger: 'blur' }],
  passphrase: [{ required: true, message: '请输入', trigger: 'blur' }],
  api_secret: [{ required: true, message: '请输入', trigger: 'blur' }],
  platform_id: [{ required: true, message: '请输入', trigger: 'blur' }],
});
const dataFormRef = ref();

interface Group {
  id: number;
  name: string;
}

const groups = ref<Group[]>([]);

const getGroupList = async () => {
  const groupList = await reqGroupList();
  groups.value = collectGroups(groupList.list);
};

const getDetails = (id: number) => {
  reqAccountDetail(id).then((res) => {
    curRowData.value = { ...res, group_id: res.group_id[0] };

    dialogVisible.value = true;
  });
};

getGroupList();

const openDialog = (type: boolean, row: any) => {
  isAddType.value = type;
  if (isAddType.value) {
    dialogVisible.value = true;
  } else {
    getDetails(row.id);
    dialogVisible.value = true;
  }
};

const closeDialog = () => {
  curRowData.value = {
    id: 0,
    ip: '',
    remark: '',
    groups: '',
    platforms: '',
    platform_id: '',
    account: '',
    status: false,
    connect: false,
    default: false,
    updated_at: '',
    group_id: '',
    api_key: '',
    api_secret: '',
    passphrase: '',
  };
};

const editConfirm = () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const submitParams = {
        ...curRowData.value,
        group_id: curRowData.value.group_id.id,
        platform_id: curRowData.value.platform_id.id,
        id: isAddType.value ? '' : curRowData.value.id,
      };

      if (isAddType.value) {
        submitParams.platform_id = curPlatformID.value;
        await addAccount(submitParams);
        ElMessage({ message: '添加成功', type: 'success' });
      } else {
        await editAccount(submitParams.id, submitParams);
        ElMessage({ message: '修改成功', type: 'success' });
      }

      dialogVisible.value = false;
      reload();
    }
  });
};

const deleteAccount = (rowID: number) => {
  ElMessageBox.confirm('确定进行删除操作?', '提示', {
    type: 'warning',
  }).then(async () => {
    await deleteAccountByID(rowID);
    ElMessage({ type: 'success', message: '操作成功' });
    reload();
  });
};
</script>

<template>
  <div class="page-content h-full">
    <div class="flex justify-between space-x-3">
      <el-radio-group
        v-model="curPlatformID"
        size="large"
        @change="handlePlatformChange"
      >
        <el-radio-button
          v-for="item in platformList"
          :label="item.name"
          :value="item.id"
          :key="item.id"
          value-key="id"
        >
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>

      <div class="flex space-x-3">
        <el-button
          :icon="Plus"
          type="primary"
          class="add-btn"
          @click="openDialog(true, {})"
        >
          新增
        </el-button>
        <BatchAdd :platform-id="curPlatformID" @reload="reload" />
        <el-button
          type="primary"
          class="add-btn"
          @click="initAccount(0, 'all')"
        >
          全部初始化
        </el-button>
      </div>
    </div>

    <div></div>
    <Grid>
      <template #status="scope">
        <el-tag :type="scope.row.status ? 'success' : 'danger'">
          {{ scope.row.status ? '启用' : '停用' }}
        </el-tag>
      </template>
      <template #connect="scope">
        <el-tag :type="scope.row.connect ? 'success' : 'danger'">
          {{ scope.row.connect ? '已连接' : '未连接' }}
        </el-tag>
      </template>
      <template #init="scope">
        <el-tag :type="scope.row.default ? 'success' : 'danger'">
          {{ scope.row.default ? '已初始化' : '未初始化' }}
        </el-tag>
      </template>
      <template #time="scope">
        {{ dayjs(scope.row.updated_at).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #action="scope">
        <!-- <el-button type="link">编辑</el-button> -->
        <el-button @click="openDialog(false, scope.row)" type="primary" link>
          编辑
        </el-button>
        <el-button @click="deleteAccount(scope.row.id)" type="danger" link>
          删除
        </el-button>
        <el-button @click="initAccount(scope.row.id)" type="success" link>
          初始化
        </el-button>
      </template>
    </Grid>
    <el-dialog
      v-model="dialogVisible"
      :title="isAddType ? '新增账号' : '编辑账号'"
      width="800"
      destroy-on-close
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        class="form"
        :model="curRowData"
        :rules="dataRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="挂靠IP" prop="ip">
          <el-input
            v-model="curRowData.ip"
            maxlength="50"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="组别" prop="group_id">
          <el-select
            v-model="curRowData.group_id"
            placeholder="请选择组别"
            value-key="id"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in groups"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="平台" prop="platform">
          <el-input v-model="curPlatform.name" placeholder="" disabled />
        </el-form-item>

        <el-form-item label="uid" prop="account">
          <el-input v-model="curRowData.account" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="key" :prop="isAddType ? 'api_key' : ''">
          <el-input
            v-model="curRowData.api_key"
            :placeholder="isAddType ? '请输入' : '加密字段不予展示'"
          />
        </el-form-item>

        <el-form-item label="Secret" :prop="isAddType ? 'api_secret' : ''">
          <el-input
            v-model="curRowData.api_secret"
            :placeholder="isAddType ? '请输入' : '加密字段不予展示'"
          />
        </el-form-item>

        <el-form-item
          label="passphrase"
          :prop="isOkxSwap ? 'passphrase' : ''"
          v-if="isOkxSwap"
        >
          <el-input v-model="curRowData.passphrase" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="curRowData.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>

        <el-form-item label="账号备注" prop="remark">
          <el-input
            v-model="curRowData.remark"
            maxlength="16"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>

      <!-- <AccountDetail
        :platform-list="platformList"
        :platform="curPlatform"
        :row-data="rowData"
      /> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- <Edit
      v-model:visible="isVisible"
      v-if="isVisible"
      :is-add="isAdd"
      :current="current"
    /> -->
  </div>
</template>

<style lang="scss" scoped>
.page-content {
  padding: 20px;
  background-color: hsl(var(--background));
  border-radius: 4px;
}

.add-btn {
  margin: 0 0 16px;
}
</style>
